<?php

declare(strict_types=1);

namespace App\Process;

use App\Amqp\Producer\DelayDirectProducer;
use Hyperf\Amqp\Producer;
use Hyperf\Process\AbstractProcess;
use Hyperf\Process\Annotation\Process;
use App\Amqp\Producer\QueueProducer as AmqpQueueProducer;
use Hyperf\Context\ApplicationContext;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Di\Annotation\Inject;

#[Process(name: 'QueueProducer')]
class QueueProducer extends AbstractProcess
{
    private $message_id = 0;

    #[Inject]
    private LoggerFactory $logger;

    public function handle(): void
    {
        while (true) {
            $this->message_id++;
            $data = ['message_id' => $this->message_id];
            if (\rand(0, 20) == 6) {
                $data['create_time'] = \date('Y-m-d H:i:s');
                $message = new DelayDirectProducer($data);
                $message->setDelayMs(rand(1000, 10000));
            } else {
                $message = new AmqpQueueProducer($data);
            }

            $producer = ApplicationContext::getContainer()->get(Producer::class);
            if ($producer->produce($message)) {
                $this->logger->get('queue')->info('Send message ' . $this->message_id . ' success.');
            } else {
                $this->logger->get('queue')->info('Send message ' . $this->message_id . ' failed.');
            }
            sleep(1);
        }
    }
}
